
require 'will_paginate'
#START:validate
#START:select
#START:has_many
class Order < ActiveRecord::Base
  #END:select
  #END:validate
  
  has_many :lines, :foreign_key => 'order_num', :class_name => 'Line'
  #END:has_many
  cattr_reader :per_page
  @@per_page = 10

  #START:select  
  STATUS_TYPES = [
    #  Displayed        stored in db
    [ "ON",          "on" ],
    [ "OFF",      "off"   ]
  ]
  
  # ...
  #END:select

  #START:validate
  validates_presence_of :order_num, :customer, :payment
  validates_numericality_of :delv_price, :delv_cost, :sum_rmb
  #  validates_inclusion_of :pay_type, :in => PAYMENT_TYPES.map {|disp, value| value}
  

  def before_update    
    #    puts "before_update_order: " + self.order_num
    self.total_amount = self.delv_price
    self.total_cost = self.delv_cost
    
    Line.find_all_by_order_num(self.order_num).each do |line|
      self.total_amount += line.sum_sales
      self.total_cost += line.sum_cost
    end
    
    self.profit = self.sum_rmb - self.total_cost    
    #    puts "total: #{total_amount}",self.total_amount    
  end
  
  def self.search( args, page)   
    paginate args, :per_page => 10, :page => page
  end
  
  #START:has_many  
end
#END:has_many
